<template>
	<view class="tea-room-detail-app">
		<view class="tea-item">
			<!--
			<image v-if="!room.images" style="width: 750upx;height:500upx;background-color: #eee;"></image>
			-->
			<!--
			<swiper class="swiper" :indicator-dots="true" :autoplay="false" interval="2000" duration="500">
				<swiper-item style="width:750upx;height: 750upx;">
					<image v-if="room.images" :src="'http://admin.zhongax.com/image/getByImageId?imageId='+room.images" style="width: 750upx;height:750upx;"></image>
					<image v-if="!room.images" style="background-color: #eee;"></image>

				</swiper-item>
			</swiper>
			-->
			<image v-if="room.images" :src="room.images" style="width: 750upx;height:750upx;"></image>
			<image v-if="!room.images" style="background-color: #eee;"></image>


			<view class="title" style="display: flex;padding: 20upx;background-color: white;">
				<text class="room-name" style="font-size: 32upx;font-weight: bold;flex:1;">{{room.roomName}}</text>
				<text class="price" style="font-size: 32upx;"><text style="color:red;">{{roomConfig.price/100}}</text>元/小时</text>
			</view>
			<!--
			<view class="tabs">
				<view class="tab-item tab-item-current">在线预约</view>
				<view class="tab-item">现场预约</view>
			</view>
			-->

			<view class="info-item select-date" style="background-color: white;margin-top:20upx;">
<!--				<my-tabs :items="tab.items" :value="tab.current" :fixed="false" @onTabChange="onTabChange" ref="typeTabs" style="background-color: white;"></my-tabs>-->
				<view class="head" style="margin-top:20upx;">
<!--					<view class="icon"><image src="/static/date.png" style="width:40upx;height:40upx;margin-top:10upx;" /></view>-->
<!--					<view class="info">请选择预约时间</view>-->
				</view>
				<view class="content"  @click="showDetail=true">

					<view v-if="!confirmInfo.defaultHourStart && !confirmInfo.defaultHourEnd" class="date-tip" style="margin-bottom: 20upx;">
<!--            <view class="icon"><image src="/static/date.png" style="width:40upx;height:40upx;margin-top:10upx;" /></view>-->
            请选择预约时间
            <view class="triangle-down"></view></view>
					<view v-if="confirmInfo.defaultHourStart && confirmInfo.defaultHourEnd" class="date-tip" style="margin-bottom: 20upx;">
<!--            <view class="icon"><image src="/static/date.png" style="width:40upx;height:40upx;margin-top:10upx;" /></view>-->
            {{confirmInfo.defaultHourStart}} ~ {{confirmInfo.defaultHourEnd}}
            <view class="triangle-down"></view>
          </view>

				</view>

			</view>
			<view class="select-date" style="background-color: white;margin-top:20upx;">
				<view class="head">
					<view class="icon"><image src="/static/doc.png" style="width:40upx;height:40upx;margin-top:10upx;" /></view>
					<view class="info">使用说明</view>
				</view>
				<view class="content" style="margin:20upx;font-size: 28upx;">
					<!--
					<rich-text :nodes="article.content"></rich-text>
					-->
					<view class="value-item">普通用户消费标准包厢每小时{{roomConfig.price/100}}元，2小时起。</view>
					<!--
					<view class="value-item">需要先支付押金500.00元，消费后余额退还。</view>
					-->
					<view class="value-item">成为会员可享受更多优惠</view>
					<!--
					<view class="submit-button">
						了解会员详情
					</view>
					-->
				</view>
			</view>
		</view>
		<view class="buttons">
			<view class="price-info">
				<view class="price">¥{{confirmInfo.totalPrice}}</view>
				<view class="total-hours">共{{confirmInfo.hour}}小时</view>
			</view>
			<view class="button" @click="confirmOrder">去结算</view>
		</view>
		<!--
		<mx-date-picker :show="showPicker" :type="type" :value="value" :show-tips="true" :begin-text="'开始'" :end-text="'结束'" :show-seconds="false" @confirm="ed" @cancel="ed" />

		-->
		<view class="background-fix" v-if="showDetail" @click="showDetail=false"></view>
		<view class="appointment-select" v-if="showDetail">
			<view class="notice-tip"><image class="notice-image" src="../../../static/notice.png" />2小时起订，灰色为已被预订</view>
			<view class="date-select">
				<view class="date-select-item" @click="selectDay(defaultItem)" :class="{current:defaultItem.selected?true:false}" v-for="(defaultItem,key) in selectOptions.defaultDayList" :key="key">
					<view class="month">{{defaultItem.day}}</view>
					<view class="week">{{defaultItem.week}}</view>
				</view>
				<view class="date-select-item" @click="selectCustomDay">
					<view class="month">
						<image src="../../../static/cal.png" class="cal-image"></image>
					</view>
					<view class="week">其它日期</view>
				</view>
			</view>
      <view class="quick-select">
        <view class="quick-select-btn" @click="quickSelectHour(2)">2小时</view>
        <view class="quick-select-btn" @click="quickSelectHour(4)">4小时</view>
        <view class="quick-select-btn" @click="quickSelectHour(6)">6小时</view>
      </view>
			<view class="hours">
        <view v-for="(defaultHour,index) in selectOptions.defaultHourList" v-if="!defaultHour.pass">
          <view v-if="!defaultHour.disabled && defaultHour.hour != '24:00'" @click="selectHour(defaultHour)" class="hour" :class="{current:defaultHour.selected?true:false}">
            <div style="margin-top: -6rpx">{{getPrice(defaultHour.hour)}}元</div>
            <div style="font-size: 24rpx;margin-top: 6rpx">{{defaultHour.hour + "-" + selectOptions.defaultHourList[index + 1].hour}}</div>
          </view>
          <view v-if="defaultHour.disabled && defaultHour.hour != '24:00'" class="hour" :class="{current:defaultHour.selected?true:false}" style="background: lightgrey;">
            <div style="margin-top: -6rpx">{{getPrice(defaultHour.hour)}}元</div>
            <div style="font-size: 24rpx;margin-top: 6rpx">{{defaultHour.hour + "-" + selectOptions.defaultHourList[index + 1].hour}}</div>
          </view>
        </view>
			</view>
			<view class="select-buttons">
				<view class="close-button" @click="showDetail=false">取消</view>
				<view class="confirm-button" @click="confirmSelect">确定({{orderHour}}小时)</view>
			</view>
		</view>

		<w-picker
			:visible.sync="visible"
			mode="date"
			startYear="2021"
			endYear="2029"
			value="selectOptions.startDate"
			:current="true"
			fields="day"
			@confirm="onDateConfirm($event,'date')"
			@cancel="onCancel"
			:disabled-after="false"
			ref="date"
		></w-picker>

		<modal :show="orderConfirmDailog.show"  @close="orderConfirmDailog.show=false;couponState = false;" @cancel="orderConfirmDailog.show=false;couponState = false" @confirm="toPay" :show-cancel="true" confirm-text="确定" cancel-text="关闭">
			<!--
			<view class="dialog-head">确认订单</view>
			-->
			<view class="app-info-dialog" style="padding:30upx;width: 80%">

				<view class="info-field">
					<view class="tit">房间名：</view>
					<view class="value">{{room.roomName}}</view>
				</view>
				<view class="info-field">
					<view class="tit">开始时间：</view>
					<view class="value">{{confirmInfo.defaultHourStart}}</view>
				</view>
				<view class="info-field">
					<view class="tit">结束时间：</view>
					<view class="value">{{confirmInfo.defaultHourEnd}}</view>
				</view>
				<view class="info-field">
					<view class="tit">服务时长：</view>
					<view class="value">{{confirmInfo.hour}}小时</view>
				</view>
				<view class="info-field">
					<view class="tit">包间费：</view>
					<view class="value">{{confirmInfo.totalPrice}}元</view>
				</view>

				<view class="info-field">
					<view class="tit">卡券:</view>
					<view v-if="!selectedCoupon" class="value" style="color: orange" @click="handleShowCoupon">{{couponList.length}}张可用></view>
					<view v-if="selectedCoupon" class="value" style="color: orange" @click="handleShowCoupon">{{selectedCoupon.voucherName}}</view>
				</view>
				<view class="info-field" v-if="couponInfo.title">
					<view class="tit">美团券:</view>
					<view class="value">{{couponInfo.title}}</view>
				</view>
        <view class="info-field">
          <view class="tit">优惠金额：</view>
          <view class="value">{{confirmInfo.discountAmount}}元</view>
        </view>
        <view class="info-field">
          <view class="tit">合计：</view>
          <view class="value" style="color: orange;font-weight: bold">{{confirmInfo.totalPrice - confirmInfo.discountAmount}}元</view>
        </view>
			</view>
		</modal>

		<modal :show="sceneConfirmDialog.show"  @close="onSceneClose" @cancel="onSceneClose" @confirm="scenePay" :show-cancel="true" confirm-text="确定" cancel-text="关闭">
			<view class="form-items scene-confirm-form">
				<!--
				<view class="form-item">
					<view class="form-title">当前时间:</view>
					<view class="form-value">2022-05-06 21:27</view>
				</view>
				-->
				<view class="form-item">
					<view class="form-title">预约:</view>
					<view class="form-value">
						<picker @change="onScenePickerChange" :value="sceneConfirmDialog.hourIndex" :range="sceneConfirmDialog.hourArr">
							<view class="uni-input">{{sceneConfirmDialog.hourArr[sceneConfirmDialog.hourIndex]}}小时 <text style="color:#1D2C6D;margin-left:20upx;">请选择</text></view>
						</picker>
					</view>
				</view>
				<view class="form-item">
					<view class="form-title">费用:</view>
					<view class="form-value">
						{{sceneConfirmDialog.hour*roomConfig.price/100}}元
					</view>
				</view>
				<view class="form-item" v-if="couponInfo.title">
					<view class="form-title">优惠券:</view>
					<view class="form-value">
						{{couponInfo.title}}
					</view>
				</view>
			</view>
		</modal>


    <view class="coupon">
      <view :class="{'coupon-box': couponState}" @click="handleHiddenCoupon">
      </view>
      <view class="coupon-item" :class="{'coupon-show': couponState}">
        <view class="coupon-to">
          <text>选择优惠券</text>
        </view>
        <view class="content">
          <view v-if="couponList.length > 0" class="block" v-for="(item, index) in couponList" :key="index" @click="selectCoupon(item)">
            <image src="../../../static/coupon_icon.png" mode="aspectFill" class="coupon-icon"></image>
            <view class="coupon-desc">
              <view class="coupon-name">{{item.voucherName}}</view>
              <view style="display: flex">
                <view class="coupon-times">剩余{{item.times}}次</view>
                <view class="coupon-used">已用{{item.usedTimes}}次</view>
              </view>
              <view class="coupon-validity">{{filterTime(item.validityTimeStart) + '至' + filterTime(item.validityTimeEnd)}}</view>
            </view>
          </view>
          <view v-if="couponList.length == 0" style="text-align: center;padding: 10px;width: 100%;color: lightgray;font-size: 14px;">
            暂无可用优惠券
          </view>
        </view>
        <view class="cancel" @click.stop="handleHiddenCoupon">
          <text>取消</text>
        </view>
      </view>
    </view>
	</view>
</template>

<script>
	import util from '@/libs/util.js'
	import globalConfig from '../../../config'
	const baseHttp = globalConfig.API_HOST
	//import MxDatePicker from "@/components/mx-datepicker/mx-datepicker.vue";
	import wPicker from "@/components/w-picker/w-picker.vue";
	import Modal from '@/components/neil-modal/neil-modal.vue';
	import MyTabs from '@/components/my-tabs.vue'

	export default {
	    data() {
	        return {
				mtCode: '',
				tab: {
					current: 0,
					items: [
						{value:0,label:'在线预约'},
						{value:1,label:'现场预约'},
					]
				},
        couponState: false,
        selectedCoupon:null,
        couponList: [],
				sceneConfirmDialog: {
					show: false,
					hour: 2,
					hourIndex: 0,
					hourArr: [2,3,4,5,6,7,8,9,10,11,12],
					totalPrice: 0.00
				},
				orderConfirmDailog: {
					show: false
				},
				showDetail: false,
                showPicker: false,
                date: '2019/01/01',
                time: '15:00:12',
                value: '',
				currentDay: '',
				maxHour: 0,
				confirmInfo: {
					startYear: '',
					startDate: '',
					defaultHourStart: '',
					defaultHourEnd: '',
					hour: 0,
          discountAmount: 0,
					totalPrice:0
				},
        dayTimeJson: {},
        bookedTimeJson: [],
				selectOptions: {
					startDate: "",
					defaultDayList:[],
					defaultHourStart: '',
					defaultHourEnd: '',
					defaultHourList: []
				},
				baseHttp: baseHttp,
				teaHouseId: '',
				roomId: '',
				showCount: 0,
				orderHour: 0,
				map: {

				},
				user: {
					level: 0
				},
				isUseCoupon: false,
				couponInfo: {
					code:"",
					price:0,
					time:0,
					title:"",
					type:""
				},
				room: {
					roomId: "",	//包厢id
					teamhouseId: "",	//茶室id
					roomType: "",	//包厢类型（预留）
					roomLevel: "",	//包厢等级（预留）
					roomState: "",	//包厢状态
					roomNO: "",	//包厢编号
					roomName: "",	//包厢名称
					images: "",	//包厢图片
					updateTime: "",	//更新时间
					remark: "",	//备注
					orderUserId: "",	//预约用户ID
					orderTime: ""	//预约时间
				},
        timeIntervalDiscountJSON: {},
				roomConfig: {
					roomId: "",	//包厢id
					price: "",	//包厢租用单价（分）每小时
					vipPrice: "",	//会员包厢租用单价（分）每小时
					lockerPrice: "",	//储物柜租用单价（分）每小时
					freeOrderTime: "",	//免费预约时间（分）
					remark: ""	//备注
					/*
					deposit: "",
					vipMoney: "",
					money: "",
					superVipTimes: "",
					subMemberLimit: "",
					remark: ""
					*/
				},
				listData: {
					items: [

					]
				}
	        }
	    },
		onLoad(params) {
			this.roomId = params.roomId;
			this.mtCode = params.mtCode;
			if (this.mtCode=="undefined") {
				this.mtCode = "";
			}
		},
		onShow() {
      let page = this;

      const date = new Date()
      const year = date.getFullYear()
      page.confirmInfo.startYear = year;
			this.getRoomDetail(this.roomId);
			this.getRoomConfig(this.roomId);
			this.getCurrentDate();

			this.getCouponInfo();
      setTimeout(function () {
        page.getCardAndVoucher();
      }, 3000)
		},
		components: {
			//MxDatePicker
			wPicker,
			Modal,
			MyTabs
		},
		computed: {

		},
	    methods: {
			...util,

      // 显示优惠券
      handleShowCoupon () {
        if(!this.mtCode) {
          this.couponState = true;
        }
      },
      // 隐藏优惠券
      handleHiddenCoupon () {
        this.couponState = false;
      },
      getPrice(hour) {
        if(hour == "24:00") {
          hour = "00:00"
        }
        var item = this.timeIntervalDiscountJSON[hour];
        if(item) {
          if(item.discountType == 1 && item.discountValue < 10) {
            return (item.discountValue * this.roomConfig.price/100/10/2).toFixed(2)
          } else if(item.discountType == 2 && item.discountValue > 0) {
            return ((this.roomConfig.price/100 - item.discountValue)/2).toFixed(2)
          } else {
            return this.roomConfig.price/100/2
          }
        } else {
          return this.roomConfig.price/100/2
        }
      },
      selectCoupon (coupon) {
        //选择优惠券
        this.couponState = false;
        var totalAmt = this.roomConfig.price * this.confirmInfo.hour;
        if(coupon.voucherType == 1 || coupon.voucherType == 4 || coupon.voucherType == 5 || coupon.voucherType == 6) {
          this.confirmInfo.discountAmount = ((coupon.voucherValue/100) * this.roomConfig.price/100).toFixed(2);
        } else if(coupon.voucherType == 2) {
          this.confirmInfo.discountAmount = ((totalAmt - coupon.voucherValue/100/10 * totalAmt)/100).toFixed(2);
        } else if(coupon.voucherType == 3) {
          if(totalAmt < coupon.lessValue) {
            this.$Message.error("满" + coupon.lessValue/100 + "元可用！");
            return
          }
          this.confirmInfo.discountAmount = (coupon.voucherValue/100).toFixed(2);
        }

        this.confirmInfo.couponId = coupon.id;
        this.selectedCoupon = coupon
      },
      getCardAndVoucher() {
        this.$api.post('/user/voucher/getUserVoucher', {}).then((response) => {
          if (response.ret===1) {
            this.couponList = response.data;
          }
        });
			},
			getCouponInfo() {
				if (this.mtCode && this.mtCode!='undefined') {
					this.$api.post('/mtconfig/getCodeInfo', {
						code: this.mtCode
					}).then((response) => {
						if (response.ret===1) {
							this.couponInfo = response.data;
						} else {
							this.$Message.error(response.msg)
						}
					});
				} else {
					//this.$Message.error("请输入团购码");
				}
			},
			scenePay() {
				let timestamp = Date.parse(new Date());
				timestamp = timestamp / 1000 + 10;
				let currentDate = this.timeToDate(timestamp);//当前时间
				let hour = this.sceneConfirmDialog.hour;
				this.toPay(currentDate, hour, hour * this.roomConfig.price/100);
			},
			onScenePickerChange(e) {
				//场景
				this.sceneConfirmDialog.hourIndex = e.detail.value;
				this.sceneConfirmDialog.hour = this.sceneConfirmDialog.hourArr[e.detail.value];
			},
			onTabChange(value) {

				if(value==1) {
					this.sceneConfirmDialog.show = true;
				}

				//this.tab.current = 0
			},
			onSceneClose() {
				this.sceneConfirmDialog.show = false;
				this.$refs.typeTabs.setCurrent(0);
			},
			checkCurrentHour() {
				let startTime = parseInt((new Date()).valueOf()/1000);
				let currentDay = this.timeToDay(startTime);
				if (currentDay==this.selectOptions.startDate) {
					let date = new Date();
					let hour = date.getHours();
					let minutes = date.getMinutes();
          if(minutes < 15) {
            this.maxHour = hour * 60;
          } else if(minutes >= 15 && minutes < 45) {
            this.maxHour = hour * 60 + 30;
          } else if(minutes >= 45 && minutes <= 59) {
            this.maxHour = (hour + 1) * 60;
          }
				} else {
					this.maxHour = 0;
				}
			},
			onCancel() {

			},

      filterTime(time) {
        const date = new Date(time)
        const Y = date.getFullYear()
        const M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1
        const D = date.getDate()
        return `${Y}-${M}-${D}`
      },

			toPay(startDate, hour, totalPrice) {
				let payTotalPrice = 0.00;
				if (totalPrice) {
					payTotalPrice = totalPrice;
				} else {
					payTotalPrice = this.confirmInfo.totalPrice;
				}

				if (payTotalPrice<=0) {
					this.$Message.error("订单金额不能为0");
					return false;
				}
        payTotalPrice = payTotalPrice - this.confirmInfo.discountAmount;
				wx.login({
					success: (res) => {
						if (res.code) {
							let wxCode = res.code;
							let payStartDate = '';
							let payHour = '';

							if (startDate) {
								payStartDate = startDate;
							} else {
								payStartDate = this.confirmInfo.startYear + "-" + this.confirmInfo.defaultHourStart.replace("月","-").replace("日","")+":00";
							}

							if (hour) {
								payHour = hour;
							} else {
								payHour = this.confirmInfo.hour;
							}

							//判断选择时间一段，要跟团购券一样
							//this.couponInfo.code;
							if (this.couponInfo.code) {
								let couponInfoHour = this.couponInfo.time;
								if (couponInfoHour!=payHour) {
									this.$Message.error("选择时长需要跟团购券时长一致");
									return false;
								}
							}

							//mtCode
							let payParams = {
								code: wxCode,
								roomId: this.roomId,
								startTime: payStartDate,// "2021-12-26 18:00:00",
								hours: payHour,
								mtCode: this.mtCode,
                couponId: this.confirmInfo.couponId
							}

							this.$api.post('/roomOrder/roomOrder',
								payParams
							).then((response) => {
							  if (response.ret===1) {
								if (response.data===null || response.data===undefined || response.data==="ok" ) {
									//会员支付成功
									//this.$Message.success("支付成功");

									this.goPage("/pages/tea/default/paySuccess");
								} else {
									let json = "{"+response.data+"}";
									json = json.replace(/'/g,'"');
									json = JSON.parse(json);

									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: json.timeStamp,
										nonceStr: json.nonceStr,
										package: json.package,
										signType: json.signType,
										paySign: json.paySign,
										success:  (res) => {

											this.goPage("/pages/tea/default/paySuccess");

										},
										fail: function (err) {
											console.log('fail:' + JSON.stringify(err));
										}
									});
								}


							  } else {

								  if ((response.data===null || response.data===undefined)&&response.msg=="会员费不足，请充值") {
									//"msg":"会员费不足，请充值"
									this.$Message.error(response.msg);

									setTimeout(()=>{
										this.goPage("/pages/user/info/vip");
									},2000);
								  } else if ((response.data===null || response.data===undefined)&&response.msg=="余额不足，请先充值") {
                    this.$Message.error(response.msg);
                    setTimeout(()=>{
                      this.goPage("/pages/user/info/vip?teaHouseId=" + this.room.teaHouseId);
                    },2000);
                  } else {
									 this.$Message.error(response.msg)
								  }
							  }
							});
						}
					}
				});

			},
			confirmOrder() {
				if (this.confirmInfo.hour==0) {
					this.$Message.info("请选择预约时间");
				} else if (this.confirmInfo.hour==1) {
					this.$Message.info("2小时起订");
				} else {
					this.orderConfirmDailog.show = true;

          if(this.couponList.length > 0) {
            if(!this.mtCode) {
              this.couponState = true;
            }
          }
				}

			},
			confirmSelect() {
				let calItem = this.orderHour - Math.floor(this.orderHour);
				let confirmHour = this.calHour("select");
				if (calItem==0.5) {
					this.$Message.info("预约小时必须为整数");
				} else if (confirmHour<=1){
					this.$Message.info("2小时起订");
				} else {
					this.confirmInfo.startDate = this.selectOptions.startDate;// '2022-01-07',
					this.confirmInfo.hour = confirmHour;
          var totalPrice = 0;
          for(let i = 0; i<this.selectOptions.defaultHourList.length;i++) {
            var item = this.selectOptions.defaultHourList[i];
            if(item.selected) {
              var hourPrice = this.getPrice(item.hour)
              totalPrice = (totalPrice/1) + (hourPrice/1);
            }
          }
          // this.confirmInfo.defaultHourEnd = this.confirmInfo.defaultHourEnd
					this.confirmInfo.totalPrice = (this.confirmInfo.hour * (this.roomConfig.price / 100)).toFixed(2);
          this.confirmInfo.discountAmount = (this.confirmInfo.totalPrice - (totalPrice/1)).toFixed(2)
					this.showDetail = false;
          this.confirmOrder()
				}
			},
			onDateConfirm(day) {
				this.selectOptions.startDate = day.result;
				this.getCurrentDate(day.result);
			},
			selectCustomDay() {
				this.$refs.date.show();
			},
			quickSelectHour(timeLong) {
        var index = timeLong * 2;
        var count = timeLong * 2;
        this.confirmInfo.defaultHourStart = '';
        this.selectOptions.defaultHourList.forEach(item => {
          item.selected = false;
          if(!item.pass && !item.disabled && index == count) {
            this.selectHour(item);
            index --;
          } else if(index < count && index > 1) {
            index --;
          } else if(index == 1) {
            this.selectHour(item);
            index --;
          }
        })
      },
			selectHour(defaultHour) {
        let page = this;
        var startTimeFLag = false;
        if(!page.confirmInfo.defaultHourStart) {
          page.confirmInfo.defaultHourStart = defaultHour.day + " " + defaultHour.hour;
          startTimeFLag = true;
        } else {
          page.confirmInfo.defaultHourEnd = defaultHour.day + " " + defaultHour.hour;
        }

        if(!startTimeFLag && this.confirmInfo.defaultHourStart == defaultHour.day + " " + defaultHour.hour) {
          page.selectOptions.defaultHourList.forEach(function (item) {
            item.selected = false;
          });
          page.confirmInfo.defaultHourStart = '';
        }

        var startFlag = false;
        var endFlag = false;
        page.selectOptions.defaultHourList.forEach(function (item) {
          item.selected = false;
          var itemTime = item.day + " " + item.hour;
          if(page.confirmInfo.defaultHourStart == itemTime) {
            startFlag = true;
            item.selected = true;
          }
          if(page.confirmInfo.defaultHourEnd == itemTime) {
            endFlag = true;
            item.selected = true;
          }

          if(!startTimeFLag && startFlag && !endFlag) {
            item.selected = true;
          }
        });
				this.orderHour = this.calHour();
			},
			calHour(dateType="select") {
				//计算预约了多少个小时
        var count = 1;
        var day = "";
        var dayCount = 0;
        this.selectOptions.defaultHourList.forEach(function (item) {
          if(item.selected && day == "") {
            day = item.day;
            dayCount ++;
          }
          if(item.selected && day != item.day) {
            dayCount ++;
            day = item.day;
          }
          if(item.selected) {
            count ++;
          }
        });

        return count > 0 ? (count - dayCount)/2 : 0;
			},
			selectDay(defaultItem) {
        let page = this;
        var day = defaultItem.day;

        // 查询预订情况
        this.$api.post('/roomOrder/bookingDetail',
            {
              roomId: this.roomId,
              day: defaultItem.year + "-" + day,
            }
        ).then((response) => {
          if (response.ret===1) {
            this.confirmInfo.startYear = defaultItem.year;

            for(let i = 0; i<this.selectOptions.defaultDayList.length;i++) {
              this.selectOptions.defaultDayList[i].selected = false;
            }
            this.selectOptions.startDate = defaultItem.day;
            defaultItem.selected = true;

            this.selectOptions.defaultHourStart = '';
            this.selectOptions.defaultHourEnd ='';
            this.checkCurrentHour();

            for(let i = 0; i<this.selectOptions.defaultHourList.length;i++) {
              this.selectOptions.defaultHourList[i].disabled = false;
              let hour = this.selectOptions.defaultHourList[i].hour;
              let itemDay = this.selectOptions.defaultHourList[i].day;
              let intHour = parseInt(hour.split(":")[0]) * 60 + parseInt(hour.split(":")[1])

              //过滤hour
              if(day != itemDay || intHour < this.maxHour) {
                this.selectOptions.defaultHourList[i].pass = true
              } else {
                this.selectOptions.defaultHourList[i].pass = false
              }
            }
            // this.orderHour = this.calHour();
            this.selectOptions.defaultHourList.forEach(function (item){
              response.data.forEach(function (bookingTime){
                page.bookedTimeJson[bookingTime] = false;
                day = day.replace("月","-").replace("日","");
                if(bookingTime == defaultItem.year + "-" + day.replace("月", "-").replace("日", "") + " " + item.hour) {
                  item.disabled = true;
                  page.bookedTimeJson[bookingTime] = true;
                }

                // if(bookingTime.lastIndexOf("00:00") > 0 && item.hour == "24:00") {
                //   item.disabled = true;
                //   page.bookedTimeJson[bookingTime] = true;
                // }
              });
            });
            // this.orderHour = this.calHour();
          } else {
            this.$Message.error(response.msg)
          }
        });
			},
			getCurrentDate(startDate = '') {
				//获取当前日期，还有后两天日期数据
				let startTime = parseInt((new Date()).valueOf()/1000);
				if (startDate) {
					startTime = parseInt((new Date(startDate)).valueOf()/1000);
				}
				let startTimeNext01 = startTime+24*3600;
				let startTimeNext02 = startTime+24*3600*2;
				let startWeekLabel = this.getWeekDate(startTime);
				let startWeekLabel01 = this.getWeekDate(startTimeNext01);
				let startWeekLabel02 = this.getWeekDate(startTimeNext02);

				let startDateLabel = this.timeToDay(startTime);
				let startDateLabel01 = this.timeToDay(startTimeNext01);
				let startDateLabel02 = this.timeToDay(startTimeNext02);

				this.selectOptions.defaultDayList = [
					{
						year: this.timeToYear(startTime),
						day: startDateLabel,
						week: startWeekLabel,
						selected: false
					},
					{
						year: this.timeToYear(startTimeNext01),
						day: startDateLabel01,
						week:startWeekLabel01,
						selected: false
					},
					{
						year: this.timeToYear(startTimeNext02),
						day: startDateLabel02,
						week:startWeekLabel02,
						selected: false
					}
				];
        this.initHours(startDateLabel, startDateLabel01, startDateLabel02);
			},

      initHours(day1, day2, day3) {
        this.generateHours(day1);
        this.selectDay(this.selectOptions.defaultDayList[0]);
        this.generateHours(day2);
        this.generateHours(day3);
      },

      generateHours(day) {
        var currMin = "00";
        var hour;
        for(var i = 0; i <= 48; i ++ ) {
          hour = Math.trunc(i/2);
          if(hour < 10) {
            hour = "0" + hour;
          }
          this.selectOptions.defaultHourList.push({
            day: day,
            hour: hour + ":" + currMin,
            disabled: false,
            pass: false,
            selected: false
          })
          if(currMin == "00") {
            currMin = "30";
          } else {
            currMin = "00";
          }
        }
      },

			timeToDay(timestamp) {
				var re = /^[0-9]+$/;
				if (!re.test(timestamp)) {
					return timestamp
				}
				var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月';
				var D = date.getDate() < 10? '0'+date.getDate() + '日' : date.getDate() + '日';
				return M+D;
			},

			timeToDayYMD(timestamp) {
				var re = /^[0-9]+$/;
				if (!re.test(timestamp)) {
					return timestamp
				}
				var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
				var D = date.getDate() < 10? '0'+date.getDate() : date.getDate();
				return M+D;
			},
			timeToYear(timestamp) {
				var re = /^[0-9]+$/;
				if (!re.test(timestamp)) {
					return timestamp
				}
				var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
				return date.getFullYear();
			},
            DatePicker(type){//显示
                this.type = type;
                this.showPicker = true;
                this.value = this[type];
            },
			ed(e) {//选择
				this.showPicker = false;
				if(e) {
					this[this.type] = e.value;
				}
			},
			getRoomDetail(id) {
				this.$api.post('/room/getById',
				  {
					roomId: id
				  }
				).then((response) => {
				  if (response.ret===1) {
					this.room = response.data
				  } else {
					this.$Message.error(response.msg)
				  }
				});
			},
			getRoomConfig(id) {
        let page = this
				//roomConfig/getById.do
				this.$api.post('/roomConfig/getById',
				  {
					roomId: id
				  }
				).then((response) => {
				  if (response.ret===1) {
					  if (response.data) {
						  this.roomConfig = response.data
              if(this.roomConfig.timeIntervalDiscount) {
                var timeIntervalDiscount = JSON.parse(this.roomConfig.timeIntervalDiscount);
                timeIntervalDiscount.forEach(function (item) {
                  page.timeIntervalDiscountJSON[item.time] = item;
                })
              }
					  } else {
						  this.roomConfig.price = 0;
					  }

				  } else {
					this.$Message.error(response.msg)
				  }
				});
			}
	    }
	}
</script>

<style lang="scss">
	page{
		/*height: 100%;*/
		background-color: #F5F4F8;
	}

	.page-section,.page-body,.tea-manager-app{
		height: 100%;
	}

	.tea-room-detail-app{
		background-color: #F5F4F8;
		color:#707070;
		padding-bottom:150upx;
		font-size:32upx;
		overflow: hidden;

		.scene-confirm-form {
			padding: 20upx;

			.form-item {
				margin-top:20upx;
				display: flex;
				.form-title{
					margin-right:20upx;
				}
				.form-value{
					flex:1;
				}
			}

		}

		.info-field{
			display:flex;
			margin-bottom: 10upx;
			.tit{
				width: 180upx;
			}
			.value{
				flex:1;
			}
		}

		.background-fix{
			background-color: black;
			opacity: 0.8;
			width: 100%;
			height: 100%;
			z-index: 10;
			position: fixed;
			top: 0;
		}

		.appointment-select{
			/*display: none;*/
			position: fixed;
			bottom: 0;
			z-index: 1000;
			height:1080upx;
			width:750upx;
			background-color: #F0F0EE;
			//border-top-left-radius: 20upx;
			//border-top-right-radius: 20upx;
			.notice-tip{
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top:20upx;
				color:#1D2C6D;
				font-weight: 500;
				.notice-image{
					width:50upx;
					height:55upx;
					margin-right:10upx;
				}
			}

			.date-select{
				display: flex;
				margin:20upx;
				font-size:28upx;
				border-radius:20upx;
				background-color: #80cbc4;
				/*

				*/
				.date-select-item{
					flex:1;
					height:120upx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					text-align: center;
					/*
					color:white;
					color:#999;*/
					&.current{
						background-color: #1D2C6D;
						border-radius:20upx;
						color:white;
					}

					.month{}
					.week{}
					.cal-image{
						width: 30upx;
						height: 30upx;
					}
				}
			}

      .quick-select {
        display: flex;
        text-align: center;
        margin: 0 auto 20rpx auto;
      }

      .quick-select-btn {
        width: 33%;
        border: 1px solid #80cbc4;
        margin: 0 20rpx;
        padding: 10rpx 0;
        border-radius: 10rpx;
      }

			.hours{
				/*
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				*/
				margin-left:20upx;
				font-size:28upx;
				overflow-y: scroll;

				height: 550upx;

				.hour{
					float:left;
          text-align: center;
					padding:20upx 18upx;
					margin-right:20upx;
					margin-bottom:20upx;
					border-radius: 10upx;
					background-color: #80cbc4;
					height: 60upx;
          width: 25%;
					&.current{
						background-color: #1D2C6D;
						color:white;
					}
				}
			}
			.select-buttons{
				position: fixed;
				bottom: 0;
				display: flex;
				justify-content: center;

				align-items: center;
				height:120upx;
				background-color: white;
				border-top: 1upx solid #eee;
				width: 100%;
				.close-button{
					width:250upx;
					border-radius: 30upx;
					background-color: #80cbc4;
					padding:20upx;
					text-align: center;
					margin-left:10upx;
				}
				.confirm-button{
					width:250upx;
					border-radius: 30upx;
					background-color: #1D2C6D;
					color:white;
					padding:20upx;
					margin-left: 30upx;
					text-align: center;
				}
			}
		}

		.date-tip{
			background-color: #FFF4E4;
			width: 550upx;
			margin:0 auto;
			padding:10upx;
			font-size: 28upx;
			text-align: center;
			margin-bottom: 10upx;
			margin-top: 10upx;
			color: #1D2C6D;
			position: relative;
			.triangle-down{
				width: 0;
				height: 0;
				border-left: 10upx solid transparent;
				border-right: 10upx solid transparent;
				border-top: 20upx solid #1D2C6D;
				position: absolute;
				right: 20upx;
				top:20upx;
			}
		}
		.select-date{
			.head{
				display: flex;
				justify-content: center;
				align-items: center;
				.info{
					font-weight: bold;
					margin-left: 10upx;
				}
			}
		}
		.buttons{
			position: fixed;
			bottom: 0;
			height:100upx;
			background-color: white;
			width:100%;
			display: flex;
			.price-info{
				flex: 1;
				.price{
					font-size:32upx;
					margin-left:30upx;
					margin-top:10upx;
				}
				.total-hours{
					font-size:28upx;
					margin-left:30upx;
				}
			}
			.button{
				width: 180upx;
				text-align: center;
				background-color: #1D2C6D;
				color:white;
				line-height: 100upx;

			}
		}
		.isOkRoom{
			color:green;
		}
		.submit-button{
			font-size:30upx;
			/*margin:0 auto;*/
			background-color:#1D2C6D;
			color:white;
			width:300upx;
			height:60upx;
			text-align: center;
			line-height: 60upx;
			margin-top:20upx;
		}
		.tea-item{
			background-color: white;
			background-color: #F5F4F8;
			/*padding: 20upx;*/
			margin-bottom:20upx;
			display: flex;
			flex-direction: column;
			position: relative;
			.image{

			}
			.map-point{
				width:120upx;
				height:120upx;
				/*background-color: white;*/
				margin-right:20upx;
			}
			.tea-house-info{
				width:100%;
				height:120upx;
				margin-top:-160upx;
				/*
				background-color: black;
				opacity: 0.5;
				*/
				background-color: rgba(0,0,0,0.5);
				padding:20upx;
				color:white;
				font-size:32upx;
				display: flex;
				.base-info{
					flex:1;
				}
				.title{
					font-weight: bold;
				}
				.address{

				}
			}
			.map-item-info{
				display: flex;
				flex-direction: column;
				.map-info{
					text-align: center;
					font-size:24upx;
					/*margin:0 auto;*/
					background-color:#1D2C6D;
					color:white;

					height:45upx;
					text-align: center;
					line-height: 45upx;
				}
			}
			.content{
				flex: 1;
				.title{
					color:#1D2C6D;
					font-size:32upx;
				}
			}
		}
		/*
		.info-item{
			background-color: white;
			display: flex;
			padding: 20upx;
			font-size:28upx;
			border-bottom: 1upx solid #eee;
			.icon{
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.value{
				margin-left:20upx;
			}
		}*/
		.room-select{
			/*
			margin-left:38upx;
			margin-right:38upx;
			*/
			margin-top:40upx;
			.head{
				font-size:32upx;
				text-indent:20upx;
			}
			.items{
				background-color: white;
				.item{
					display: flex;
					padding: 20upx;
					margin-top:20upx;
					.icon{
						width:160upx;
						height:160upx;
						margin-right:20upx;

					}
					.info{
						flex:1;
						margin-left:20upx;
						font-size:32upx;

						.name{
							font-size:32upx;
							color:#4B4B4B;
							font-weight: bold;
						}
						.number{
							font-size:28upx;
							color:#767676;
							margin-top:10upx;
						}
						.desc{
							font-size:28upx;
							color:#767676;
						}
					}

					.select-btn{
						display: none;
						background-color: #1D2C6D;
						color:white;
						width:128upx;
						height:69upx;
						line-height: 69upx;
						font-size:28upx;
						text-align: center;
					}
					.no-select-btn{
						background-color: #eee;
					}
				}
			}
		}
	}


  .coupon {
    width: 100%;
    height: 100%;
  }
  .coupon-box {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0rpx; left: 0rpx; bottom: 0rpx; right: 0rpx;
    background-color: rgba(0, 0, 0, 0.4);
    transition: .3s;
    z-index: 999;
  }
  // 进入分享动画
  .coupon-show {
    transition: all 0.3s ease;
    transform: translateY(0%) !important;
  }
  // 离开分享动画
  .coupon-item {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: auto;
    background-color: #FFFFFF;
    transition: all 0.3s ease;
    transform: translateY(100%);
    z-index: 1999;
    .coupon-to {
      width: 100%;
      height: 3rem;
      display: flex;
      justify-content: center;
      align-items: center;
      &::after {
        content: '';
        width: 240rpx;
        height: 0rpx;
        border-top: 1px solid #E4E7ED;
        -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
        margin-left: 30rpx;
      }
      &::before {
        content: '';
        width: 240rpx;
        height: 0rpx;
        border-top: 1px solid #E4E7ED;
        -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
        margin-right: 30rpx;
      }
    }
    .content {
      width: 100%;
      height: auto;
      flex-wrap: wrap;
      .block{
        height: 180rpx;
        display: flex;
        border-bottom: gainsboro 1px dashed;
        border-top: gainsboro 1px dashed;
        image {
          width: 80rpx;
          height: 80rpx;
          justify-content: center;
        }
        .coupon-desc {
          padding: 20rpx 30rpx;
          justify-content: center;
          margin-top: 16rpx;
          font-size: 28rpx;
          color: #606266;

          .coupon-name {
            display: inline-list-item;
            font-size: 32rpx;
            font-weight: bold;
          }

          .coupon-times{
            color: #1D2C6D;
            margin-top: 10rpx;
          }

          .coupon-used{
            color: orange;
            margin-left: 20rpx;
            margin-top: 10rpx;
          }

          .coupon-validity {
            display: inline-list-item;
            color: lightgrey;
            margin-top: 10rpx;
          }
        }
        .coupon-icon {
          margin-left: 36rpx;
          width: 160rpx;
          height: auto;
        }
      }
    }
    .cancel {
      width: 100%;
      height: 3rem;
      display: flex;
      justify-content: center;
      align-items: center;
      border-top: 1rpx solid #E4E7ED;
    }
  }
</style>
